package tuling.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import tuling.netty.codec.domain.CodecUser;
import tuling.netty.codec.utils.ProtostuffUtil;

/**
 * @author RenGaoshuai
 * @date 2023/12/4 10:23
 * @description
 */
public class CodecServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        String serverReply = "欢迎客户端连接，你一连接成功，请开始你的表演";
        CodecUser serverReply2 = new CodecUser("222","服务端",14);
//        ctx.writeAndFlush(serverReply2);
        ctx.writeAndFlush(Unpooled.copiedBuffer(ProtostuffUtil.serializer(serverReply2)));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        CodecUser codecUser = (CodecUser)msg;
//        System.out.println("[ 服务端接收到的数据: ]"+codecUser);
        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        System.out.println("[ 服务端接收到的数据: ]"+ProtostuffUtil.deserializer(bytes,CodecUser.class));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
